<?php
/**
 * Created by PhpStorm.
 * User: Dave
 * Date: 2018/7/18
 * Time: 20:18
 */

namespace Biz\service\activity;

use Biz\cache\FlashSaleList;
use Biz\model\activity\FlashSale as mFlashSale;
use Biz\model\activity\FlashSubscribe;
use Biz\model\activity\LimitTimeRobbing as mLimitTimeRobbing;
use Biz\model\ShopCarouselBanner;
use Biz\service\admin\LimitTimeRob;
use Biz\service\CarouselBanner;
use Biz\service\Goods as sGoods;
use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Biz\service\Activitys as sActivitys;
use Biz\cache\FlashSale as cFlashSale;
use Biz\service\Sku as sSku;
use Biz\model\activity\LimitTimeRobbingSku as mLimitTimeRobbingSku;
use Biz\service\Sku;
use Doraemon\cache\PushQueue;
use Doraemon\tools\HhzClient as tHhzClient;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\model\activity\FlashSubscribe as mFlashSubscribe;
use Biz\module\Classes\adm\FlashSaleExcel;
use Biz\module\Classes\adm\FlashSale as admFlashSale;
use Doraemon\tools\Log as tLog;
/**
 * @deprecated
 */
class FlashSale
{
	private static $isSellOut = 0;
	private static $isHasTrailer = 0;
	public static $isFlashSale = 'ing';

	public static function flashSaleIng($isPreview)
	{
		$data = [
			'time_down' => null,
			'goods_list' => [],
			'is_has_trailer' => self::$isHasTrailer
		];

		$flashSaleInfo = cFlashSale::getFlashSale(self::$isFlashSale);

		if (!$flashSaleInfo) {
			return $data;
		}

		$flashSaleInfos = cFlashSale::getFlashSale();
		if (!$flashSaleInfos['flash_sale_ing']) {
			$time = date('Y-m-d H:i:s');

			// 获取当前限时购的goods数据
			$flashSaleInfos['flash_sale_ing'] = self::getFlashSaleIngGoodsInfos($flashSaleInfo['id']);

			$goodsIds = array_column($flashSaleInfos['flash_sale_ing'], 'goods_id');
			$flashSaleInfos['start_time'] = array_shift(array_column($flashSaleInfos['flash_sale_ing'], 'start_time'));
			$flashSaleInfos['end_time'] = array_shift(array_column($flashSaleInfos['flash_sale_ing'], 'end_time'));

			$goodsSkuInfo = mLimitTimeRobbingSku::getSkuInfoByGIds($goodsIds, $time, ['goods_id', 'sku_id']);

			$flashSaleInfos['flash_sale_ing'] = array_column($flashSaleInfos['flash_sale_ing'], null, 'goods_id');

			foreach ($flashSaleInfos['flash_sale_ing'] as $value) {
				$flashSaleInfos['flash_sale_ing'][$value['goods_id']]['sku_ids'] = $goodsSkuInfo[$value['goods_id']];
			}

			// 查询是否有预告的限时购
			$flashSalePreview = mFlashSale::getFlashSalePreviewInfos($time);

			if ($flashSalePreview) {
				$previewGoodsInfos = self::getFlashSaleIngGoodsInfos($flashSalePreview['id']);
				$previewGoodsIds = array_column($previewGoodsInfos, 'goods_id');
				$flashSaleInfos['preview_goods'] = $previewGoodsIds;
				$flashSaleInfos['preview_id'] = $flashSalePreview['id'];
			}

			$expire = strtotime($flashSaleInfo['end_time']) - time();
			$flashSaleInfos['flash_sale_ing'] = array_column($flashSaleInfos['flash_sale_ing'], null, 'goods_id');

			cFlashSale::setFlashSale($flashSaleInfos, $expire);

		}

		if (isset($flashSaleInfos['preview_id']) && isset($flashSaleInfos['preview_goods'])) {
			// 每次都需要查询预告的限时抢是否全部为非正常的商品
			self::checkGoods($flashSaleInfos['preview_goods']);
		}

		$flashSaleGoodsIds = array_column($flashSaleInfos['flash_sale_ing'], 'goods_id');

		$goodsDatas = sGoods::goods($flashSaleGoodsIds, sGoods::FIELDS_GROUP_LIST, ['activity_type' => ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB]);

		$goodsDatas = self::checkSkuActivityPrice($flashSaleGoodsIds, $flashSaleInfos['flash_sale_ing'], $goodsDatas);

		if (version_compare(tHhzClient::getClientVersion(), '3.6.0', '>=')) {
			$flashSaleInfo = self::formatFlashSale3_6($goodsDatas, $flashSaleInfos, $isPreview);
		} else {
			$flashSaleInfo = self::formatFlashSale($goodsDatas, $flashSaleInfos, $isPreview);
		}

		return $flashSaleInfo ?: [];
	}


	/*
	 * 获取预告限时购商品
	 * **/
	public static function flashSalePreview()
	{
		$flashSaleInfos = cFlashSale::getFlashSale();

		$time = date('Y-m-d H:i:s');

		if ($flashSaleInfos['preview_id']) {
			$flashSaleId = $flashSaleInfos['preview_id'];
		} else {
			$flashSalePreview = mFlashSale::getFlashSalePreviewInfos($time);
			if ($flashSalePreview) {
				$flashSaleId = $flashSalePreview['id'];
			}
		}

		if ($flashSaleId) {
			$flashSaleInfos = cFlashSale::getFlashSale($flashSaleId);
			if (!$flashSaleInfos['flash_sale_ing']) {
				$flashSaleInfos['flash_sale_ing'] = self::getFlashSaleIngGoodsInfos($flashSaleId);

				$goodsIds = array_column($flashSaleInfos['flash_sale_ing'], 'goods_id');
				$flashSaleInfos['start_time'] = array_shift(array_column($flashSaleInfos['flash_sale_ing'], 'start_time'));
				$flashSaleInfos['end_time'] = array_shift(array_column($flashSaleInfos['flash_sale_ing'], 'end_time'));

				$goodsSkuInfo = mLimitTimeRobbingSku::getSkuInfoByGoodsIds($goodsIds, $time, ['goods_id', 'sku_id']);

				$flashSaleInfos['flash_sale_ing'] = array_column($flashSaleInfos['flash_sale_ing'], null, 'goods_id');

				foreach ($flashSaleInfos['flash_sale_ing'] as $value) {
					$flashSaleInfos['flash_sale_ing'][$value['goods_id']]['sku_ids'] = $goodsSkuInfo[$value['goods_id']];
				}

				$expire = strtotime($flashSaleInfos['end_time']) - time();

				cFlashSale::setFlashSale($flashSaleInfos, $expire, $flashSaleId);
				$flashSaleInfos = cFlashSale::getFlashSale($flashSaleId);
			}
		}

		$flashSaleGoodsIds = array_column($flashSaleInfos['flash_sale_ing'], 'goods_id');

		$goodsDatas = sGoods::goods($flashSaleGoodsIds, sGoods::FIELDS_GROUP_LIST, ['activity_type' => ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB]);

		$goodsDatas = self::checkSkuActivityPrice($flashSaleGoodsIds, $flashSaleInfos['flash_sale_ing'], $goodsDatas);

		if (version_compare(tHhzClient::getClientVersion(), '3.6.0', '>=')) {
			$flashSaleInfo = self::formatFlashSale3_6($goodsDatas, $flashSaleInfos, false);
		} else {
			$flashSaleInfo = self::formatFlashSale($goodsDatas, $flashSaleInfos, false);
		}

		return $flashSaleInfo;
	}

	/*
	 * 获取限时购的goods数据
	 * **/
	private static function getFlashSaleIngGoodsInfos($flashSaleId)
	{
		return mLimitTimeRobbing::getFlashSaleIngGoodsInfos($flashSaleId, ['id', 'goods_id', 'describe', 'order', 'start_time', 'end_time']);
	}

	private static function formatFlashSale3_6($list, $flashSaleInfos, $isPreview = false)
	{
		if ($list) {
			foreach ($flashSaleInfos['flash_sale_ing'] as $info) {
				$goodsDatas[$info['goods_id']] = $list[$info['goods_id']];
			}

			foreach ($list as $goodsId => $info) {
				if ($info['status'] == mGoodsBasicInfo::STATUS_APP_NOMAL) {
					$goodsData[$goodsId]['id'] = $info['id'];
					$goodsData[$goodsId]['title'] = $info['title'];
					$goodsData[$goodsId]['describe'] = $flashSaleInfos['flash_sale_ing'][$goodsId]['describe'] ?: '';
					$goodsData[$goodsId]['ori_min_price'] = $info['ori_min_price'];
					$goodsData[$goodsId]['ori_max_price'] = $info['ori_max_price'];
					$goodsData[$goodsId]['actual_min_price'] = $info['actual_min_price'];
					$goodsData[$goodsId]['actual_max_price'] = $info['actual_max_price'];
					$goodsData[$goodsId]['actual_stock'] = $info['actual_stock'];
					$goodsData[$goodsId]['activity_stock'] = $info['activity_stock'];
					$goodsData[$goodsId]['cover_img'] = $info['cover_img'];
					$goodsData[$goodsId]['status'] = mGoodsBasicInfo::STATUS_APP_NOMAL;

					// 是否卖完
					if (self::$isSellOut == 0) {
						if ($info['activity_stock'] <= 0) {
							self::$isSellOut = 1;
						}
					}
				}
			}

			$time = [
				'sys_time' => time(),
				'begin_time' => strtotime($flashSaleInfos['start_time']),
				'end_time' => strtotime($flashSaleInfos['end_time']),
			];
		}

		$flashSaleInfo['time_down'] = $time ?: null;
		$flashSaleInfo['goods_list'] = $goodsData ? array_values($goodsData) : [];

		if ($isPreview) {
			$flashSaleInfo['is_has_trailer'] = self::$isHasTrailer;
			$flashSaleInfo['is_sell_out'] = self::$isSellOut;
			$flashSaleInfo['goods_list'] = array_splice($flashSaleInfo['goods_list'], 0, 3);
		} else {
			$flashSaleInfo['cover_img'] = sActivitys::LIMIT_TIME_PAGE_COVER_IMG;
		}

		return $flashSaleInfo;
	}

	/*
	 * 构造限时购所需数据
	 * **/
	private static function formatFlashSale($list, $flashSaleInfos, $isPreview = false)
	{
		if ($list) {
			foreach ($flashSaleInfos['flash_sale_ing'] as $info) {
				$goodsDatas[$info['goods_id']] = $list[$info['goods_id']];
			}

			foreach ($list as $goodsId => $info) {
				if ($info['status'] == mGoodsBasicInfo::STATUS_APP_NOMAL) {
					$goodsData[$goodsId]['id'] = $info['id'];
					$goodsData[$goodsId]['title'] = $info['title'];
					$goodsData[$goodsId]['describe'] = $flashSaleInfos['flash_sale_ing'][$goodsId]['describe'] ?: '';
					$goodsData[$goodsId]['min_price'] = $info['min_price'];
					$goodsData[$goodsId]['max_price'] = $info['max_price'];
					$goodsData[$goodsId]['cover_img'] = $info['cover_img'];
					$goodsData[$goodsId]['status'] = mGoodsBasicInfo::STATUS_APP_NOMAL;
					// 是否卖完
					if (self::$isSellOut == 0) {
						if ($info['active_stock'] <= 0) {
							self::$isSellOut = 1;
						}
					}

//                    foreach ($info['active_list'] as $id => $item) {
//                        if ($item['type_id'] == mOrderActivityLog::ACTIVITY_TYPE_LIMIT_TIME_ROB) {
//                            $item['params']['stock'] = $info['active_stock'];

					if (!isset($time)) {
						$time = [
							'sys_time' => time(),
							'begin_time' => strtotime($flashSaleInfos['start_time']),
							'end_time' => strtotime($flashSaleInfos['end_time']),
						];
					}
					$goodsData[$goodsId]['active_top'] = (object)[
						'params' => [
							'stock' => $info['active_stock']
						]
					];

                    if (!isset($time)) {
                        $time = [
                            'sys_time' => time(),
                            'begin_time' =>  strtotime($flashSaleInfos['start_time']),
                            'end_time' =>  strtotime($flashSaleInfos['end_time']),
                        ];
                    }
                    $goodsData[$goodsId]['active_top'] = (object)[
                        'params' => [
                            'stock' => $info['active_stock']
                        ]
                    ];
				}
			}
		}

		$flashSaleInfo['time_down'] = $time ?: null;
		$flashSaleInfo['goods_list'] = $goodsData ? array_values($goodsData) : [];

		if ($isPreview) {
			$flashSaleInfo['is_has_trailer'] = self::$isHasTrailer;
			$flashSaleInfo['is_sell_out'] = self::$isSellOut;
			$flashSaleInfo['goods_list'] = array_splice($flashSaleInfo['goods_list'], 0, 3);
		} else {
			$flashSaleInfo['cover_img'] = sActivitys::LIMIT_TIME_PAGE_COVER_IMG;
		}

		return $flashSaleInfo;
	}

	/*
	 * 预告商品需要取出参与限时抢的sku的最低价和最高价
	 * **/
	private static function checkSkuActivityPrice($flashSaleGoodsIds, $flashSaleInfos, $goodsDatas)
	{
		$skuInfos = sSku::sku($flashSaleGoodsIds, sSku::FIELDS_GROUP_ALL, ['activity_type' => ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB]);

		foreach ($flashSaleInfos as $goodsInfo) {
			foreach ($goodsInfo['sku_ids'] as $skuId) {
				$skuPrice = [];
				foreach ($skuInfos[$goodsInfo['goods_id']]['sku_info'] as $skuInfo) {
					if ($skuInfo['sku_id'] == $skuId) {
						$skuPrice[] = $skuInfo['ori_price'];
						$goodsDatas[$goodsInfo['goods_id']]['min_price'] = min($skuPrice);
						$goodsDatas[$goodsInfo['goods_id']]['max_price'] = max($skuPrice);
					}
				}
			}
		}

		return $goodsDatas;
	}

	private static function checkGoods($goods)
	{
		$goodsInfos = sGoods::Goods($goods, sGoods::FIELDS_GROUP_LIST, ['activity_type' => ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB]);
		foreach ($goodsInfos as $goodsInfo) {
			if ($goodsInfo['status'] == mGoodsBasicInfo::STATUS_APP_NOMAL) {
				self::$isHasTrailer = 1;
				break;
			}
		}
	}

	public static function CronSendPush()
	{
		$flashList = self::getCacheFlashSale();
		foreach ($flashList as $flashId => $flashInfo) {
			if (strtotime($flashInfo['start_time']) > time()
				&&
				strtotime($flashInfo['start_time']) - time() <= 300
			) {
				$goodsIds = array_keys($flashInfo['goods']);
				$goodsInfos = sGoods::Goods($goodsIds);
				$subscribes= FlashSubscribe::selectInfos($flashId, $goodsIds);
				foreach ($subscribes as $subscribe) {
					if ($subscribe['is_push'] == FlashSubscribe::PUSH_NO) {
						PushQueue::insertQueue('NoticeBadge/setBadge', [
							'uid' => $subscribe['uid'],
							'title' => '「限时抢」',
							'alert' => '「'.$goodsInfos[$subscribe['goods_id']]['title'].'」正在限时秒杀中，今日「'.self::formatFlashTime($flashInfo['start_time']).'」特价¥'.$flashInfo['goods'][$subscribe['goods_id']]['buy_price'].'，快去抢购吧！',
							'param' => ['link' => "hhz://flash_sale:{\"flash_id\":" .$flashId. ", \"goods_id\":" .$subscribe['goods_id'] ."}"]
						], PushQueue::QUEUE_NOTICE_BADGE);

						FlashSubscribe::update(['is_push' => FlashSubscribe::PUSH_YES], [
							'id' => $subscribe['id']
						]);
						echo "flashId:" . $flashId . " uid:" . $subscribe['uid'] . " goodsId:" . $subscribe['goods_id'] . "\r\n";
					}
				}
			}
		}
	}

	public static function subScribeFlash($uid, $flashId, $goodsId, $isSubscribe)
	{
		$flashInfo = FlashSaleList::getFlashSale($flashId);
		if (is_null($flashInfo)) {
			$flashList = self::getCacheFlashSale();
			if(!isset($flashList[$flashId])) {
				throw new \Exception('限时购不存在');
			}
			$flashInfo = $flashList[$flashId];
		}
		if (time() + (60 * 5) > strtotime($flashInfo['start_time']) ) {
			if ($isSubscribe) {
				throw new \Exception('开抢5分钟内不能再订阅哦');
			} else {
				throw new \Exception('开抢前5分钟不能取消订阅哦');
			}
		}
		if ($isSubscribe) {
			mFlashSubscribe::saveData($flashId, $goodsId, $uid);
		} else {
			mFlashSubscribe::update(['status' => mFlashSubscribe::STATUS_DELECT], [
				'flash_id' => $flashId,
				'goods_id' => $goodsId,
				'uid' => $uid
			]);
		}
	}

	public static function flashSaleList($length = 5, $uid = 0, $param = [])
	{
		$flashSales = self::getCacheFlashSale();
		$allBanners = CarouselBanner::getMultipleBanner($uid, date("Y-m-d H:i:s"));
		$allBanners = array_column($allBanners, null, 'type');
		$results = [
			'cover_img' => sActivitys::LIMIT_TIME_PAGE_COVER_IMG,
			'banner_info' => isset($allBanners[ShopCarouselBanner::TYPE_FLASH_SALE]) ?  array_shift($allBanners[ShopCarouselBanner::TYPE_FLASH_SALE]['flash_sale']) : null,
			'list' => []
		];
		$counter = 0;
		foreach ($flashSales as $flashId => $flashSale) {
			if ($counter < $length) {
				$isSelected = 0;
				if ($param && isset($param['flash_id']) && $param['flash_id'] == $flashId) {
					$isSelected = 1;
				}
				if (!$param && $counter == 0) {
					$isSelected = 1;
				}
				$results['list'][] = [
					'id' => $flashId,
					'title' => self::formatFlashTime($flashSale['start_time']),
					'time_down' => [
						'begin_time' => strtotime($flashSale['start_time']),
						'sys_time' => time(),
						'end_time' => strtotime($flashSale['end_time']),
					],
					"is_selected" => $isSelected,
					"is_happening" => (strtotime($flashSale['start_time']) < time() && strtotime($flashSale['end_time']) > time()) ? 1 : 0
				];
			}
			$counter++;
		}
		$msg = '';
		if (!$results['list']) {
			$results['link'] = "hhz://mall_tab";
		}
		if ($param) {
			$flashId = $param['flash_id'];
			if (!in_array($flashId, array_keys($flashSales))) {
				$msg = "m:来晚一步，看看其他好物吧";
			}
		}
		return [$results, $msg];
	}

	public static function flashInfoOnShop()
	{
		$flashList = self::getCacheFlashSale();
		$flashList = array_slice($flashList, 0, 2);
		$results = [];
		foreach ($flashList as  $item) {
			$goodsList = self::flashSaleInfo($item['id']);
			$isHasStock = array_column($goodsList, 'activity_stock', 'id');
			$isHasStock = array_filter($isHasStock);
			if ($isHasStock) {
				array_multisort(array_column($goodsList, 'activity_stock'), SORT_DESC, SORT_NUMERIC, $goodsList);
				$results['time_down'] = [
					'sys_time' => time(),
					'begin_time' => strtotime($item['start_time']),
					'end_time' => strtotime($item['end_time']),
				];
				foreach ($goodsList as $k => $goods) {
					if ($k < 3) {
						$results['goods_list'][] = $goods;
					}
				}
				$results['link'] = "hhz://flash_sale:{\"flash_id\":" . $item['id'] ."}";
				break;
			}
		}
		return $results;
	}

	public static function formatFlashTime($startTime)
	{
		$date = date('Y-m-d');
		$startDate = date('Y-m-d', strtotime($startTime));
		if ($date >= $startDate) {
			return date("H:i", strtotime($startTime));
		} else if (strtotime($startDate) - strtotime($date) == 86400){
			return "明日" . date("H:i", strtotime($startTime));
		} else if (strtotime($startDate) - strtotime($date) == 86400 * 2){
			return "后天" . date("H:i", strtotime($startTime));
		} else if (strtotime($startDate) - strtotime($date) == 86400 * 3){
			return "大后天" . date("H:i", strtotime($startTime));
		}else{
		    return "";
        }
	}

	 public static function getCacheFlashSale()
	{
		$flashSaleList = FlashSaleList::getFlashListInfo();
		if (!$flashSaleList) {
			$flashSaleList = self::getDbFalshSale();
			FlashSaleList::setFlashListInfo($flashSaleList, self::calcuExpire($flashSaleList));
		}

		$flashSaleList = array_filter($flashSaleList);
		array_multisort(array_column($flashSaleList, "start_time"),$flashSaleList);
		$flashSaleList = array_column($flashSaleList, null,"id");
		return array_filter( $flashSaleList );
	}

	private static function getDbFalshSale($flashSales = []) //默认没有参数  这是为了兼容3.8
	{

		if (!$flashSales) {
			$flashSales = mFlashSale::getFlashSaleNoOverInfos();
		} else {
			$flashSales = [$flashSales]; //兼容3.8.0
		}
		$flashSales = array_column($flashSales, null, 'id');

		$flashSaleIds = array_keys($flashSales);
		$LimitTimeRobs = mLimitTimeRobbing::getFlashSaleIngGoodsInfos($flashSaleIds);
		$LimitTimeRobsGrpByFlashId = [];
		$robIds = [];
		foreach ($LimitTimeRobs as $limitTimeRob) {
			$robIds[] = $limitTimeRob['id'];
			$LimitTimeRobsGrpByFlashId[$limitTimeRob['flash_sale_id']][$limitTimeRob['goods_id']] = $limitTimeRob;
		}
		$LimitTimeRobSkus = mLimitTimeRobbingSku::getInfosByRobID($robIds);

		$flashSaleList= [];
		foreach ($flashSales as $flashId => $flashSale) {
			$flashSaleList[$flashId] = $flashSale;
			if (isset($LimitTimeRobsGrpByFlashId[$flashId])) foreach ($LimitTimeRobsGrpByFlashId[$flashId] as $goodsId => $item) {
				$LimitTimeRobsGrpByFlashId[$flashId][$goodsId]['skus'] = isset($LimitTimeRobSkus[$item['id']]) ? $LimitTimeRobSkus[$item['id']] : [];
			}
			$flashSaleList[$flashId]['goods'] = isset($LimitTimeRobsGrpByFlashId[$flashId]) ? $LimitTimeRobsGrpByFlashId[$flashId] : [];
		}

		if (!$flashSaleList) {
			$flashSaleList[] = 0;
		}
		return $flashSaleList;

	}

	private static function calcuExpire($flashSaleList) {
    	$flashSaleList = array_filter($flashSaleList);
    	if (!$flashSaleList) {
    		return 86400;
		}
		$expire = 0;
    	foreach ($flashSaleList as $item) {
    		if (!$expire || $expire > strtotime($item['end_time']) - time()) {
    			$expire = strtotime($item['end_time']) - time();
			}
		}
		return $expire;
	}

	public static function flashSaleInfo($flashId, $uid = 0)
	{
		$flashInfo = FlashSaleList::getFlashSale($flashId);

		if (!$flashInfo) {
			$flashInfo = self::getCacheFlashSale();
			if (!isset($flashInfo[$flashId])) {
				throw new \Exception('此限时购不存在');
			}
			$flashInfo = $flashInfo[$flashId];
		}

		$goodsIds = array_column($flashInfo['goods'], 'goods_id');

        $skuInfos = sSku::sku($goodsIds,sSku::FIELDS_GROUP_ALL, ['activity_type' => ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB]);

        $skuIds = [];
        foreach ($flashInfo['goods'] as $goodsId => $info) {
           if (isset($info['skus']) && $info['skus']) foreach ($info['skus'] as $skuInfo) {
                $skuIds[$goodsId][] = $skuInfo['sku_id'];
            }
        }

        foreach ($skuIds as $goodsId => $sku)
        {
            $skuPrice = [];
            foreach ($sku as $skuId) {
                foreach ($skuInfos[$goodsId]['sku_info'] as $skuInfo)
                {
                    if ($skuInfo['sku_id'] == $skuId) {
                        $skuPrice[] = $skuInfo['ori_price'];
                        $goodsDatas[$goodsId]['min_price'] = min($skuPrice);
                        $goodsDatas[$goodsId]['max_price'] = max($skuPrice);
                    }
                }
            }
        }

        $subScribes = FlashSubscribe::InfosGrpByUid($flashId, $goodsIds);
        $subScribes = $subScribes && isset($subScribes[$uid]) ? $subScribes[$uid] : [];

		$goodsInfos = sGoods::Goods($goodsIds,sGoods::FIELDS_GROUP_LIST, ['activity_type' => ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB]);
		$results = [];
		foreach ($goodsInfos as $goodsInfo) {
			if ($goodsInfo['status'] == mGoodsBasicInfo::STATUS_APP_NOMAL) $results[] = [
				'id' => $goodsInfo['id'],
				'title' => $goodsInfo['title'],
				'describe' => $flashInfo['goods'][$goodsInfo['id']]['describe'],
				'ori_min_price' => $goodsDatas[$goodsInfo['id']]['min_price'],
				'ori_max_price' => $goodsDatas[$goodsInfo['id']]['max_price'],
				'actual_min_price' => $flashInfo['goods'][$goodsInfo['id']]['buy_price'],
				'actual_max_price' => $flashInfo['goods'][$goodsInfo['id']]['buy_price'],
                'shop_id' => $goodsInfo['shop_id'],
                'category_id' => $goodsInfo['category_id'],
                'second_category_id' => $goodsInfo['second_category_id'],
				'actual_stock' =>  $goodsInfo['actual_stock'],
				'activity_stock' => $goodsInfo['activity_stock'],
				'cover_img' => $goodsInfo['cover_img'],
				'is_subscribe' => isset($subScribes[$goodsInfo['id']]) ? 1 : 0,
				'status' => $goodsInfo['status'],
			];
		}
		return $results;
	}

	/**
	 * @return array
	 *
	 * 兼容3.8 限时抢 正在进行中
	 */
	public static function flashSaleIng3_8()
	{
		$data = [
			'time_down' => null,
			'goods_list' => [],
			'is_has_trailer' => 0,
			"cover_img" => sActivitys::LIMIT_TIME_PAGE_COVER_IMG
		];
		$flashInfo = self::getCacheFlashSale();
		$dateTime = date("Y-m-d H:i:s");
		foreach ($flashInfo as $flashId => $item) {
			if ($dateTime > $item['start_time'] && $dateTime < $item['end_time']) {
				$data['time_down'] = [
					'sys_time' => time(),
					'begin_time' => strtotime($item['start_time']),
					'end_time' => strtotime($item['end_time']),
				];
				$goodsIds = array_column($item['goods'], 'goods_id');
				$goodsInfos = sGoods::Goods($goodsIds,sGoods::FIELDS_GROUP_LIST, ['activity_type' => ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB]);
				foreach ($goodsInfos as $goodsInfo) {
					if ($goodsInfo['status'] == mGoodsBasicInfo::STATUS_APP_NOMAL) $data['goods_list'][] = [
						'id' => $goodsInfo['id'],
						'title' => $goodsInfo['title'],
						'describe' => $item['goods'][$goodsInfo['id']]['describe'],
						'ori_min_price' => $goodsInfo['ori_min_price'],
						'ori_max_price' => $goodsInfo['ori_max_price'],
						'actual_min_price' => $item['goods'][$goodsInfo['id']]['buy_price'],
						'actual_max_price' => $item['goods'][$goodsInfo['id']]['buy_price'],
						'actual_stock' => $goodsInfo['actual_stock'],
						'activity_stock' => $goodsInfo['activity_stock'],
						'cover_img' => $goodsInfo['cover_img'],
						'status' => $goodsInfo['status'],
					];
				}

				break;
			}
		}
		//往下都是兼容3.8.0的显示问题
		if (!$data['goods_list']) {
			$flashInfo = mFlashSale::getPreviousFlashSale();
			$flashInfo = self::getDbFalshSale($flashInfo);
			foreach ($flashInfo as $flashId => $item) {
				$data['time_down'] = [
					'sys_time' => time(),
					'begin_time' => strtotime($item['start_time']),
					'end_time' => strtotime($item['end_time']),
				];
				$goodsIds = array_column($item['goods'], 'goods_id');
				$goodsInfos = sGoods::Goods($goodsIds, sGoods::FIELDS_GROUP_LIST, ['activity_type' => ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB]);
				foreach ($goodsInfos as $goodsInfo) {
					if ($goodsInfo['status'] == mGoodsBasicInfo::STATUS_APP_NOMAL) $data['goods_list'][] = [
						'id' => $goodsInfo['id'],
						'title' => $goodsInfo['title'],
						'describe' => $item['goods'][$goodsInfo['id']]['describe'],
						'ori_min_price' => $goodsInfo['ori_min_price'],
						'ori_max_price' => $goodsInfo['ori_max_price'],
						'actual_min_price' => $item['goods'][$goodsInfo['id']]['buy_price'],
						'actual_max_price' => $item['goods'][$goodsInfo['id']]['buy_price'],
						'actual_stock' => $goodsInfo['actual_stock'],
						'activity_stock' => $goodsInfo['activity_stock'],
						'cover_img' => $goodsInfo['cover_img'],
						'status' => $goodsInfo['status'],
					];
				}
			}
		}
		$data['is_has_trailer'] = self::flashPreview3_8()['goods_list'] ? 1 : 0;
		return $data;
	}

	/**
	 * @return array
	 *
	 * 兼容3.8 限时抢 预告
	 */
	public static function flashPreview3_8()
	{
		$data = [
			'time_down' => null,
			'goods_list' => [],
			"cover_img" => sActivitys::LIMIT_TIME_PAGE_COVER_IMG
		];
		$flashInfo = self::getCacheFlashSale();
		$dateTime = date("Y-m-d H:i:s");
		foreach ($flashInfo as $flashId => $item) {
			if ($dateTime < $item['start_time']) {
				$data['time_down'] = [
					'sys_time' => time(),
					'begin_time' => strtotime($item['start_time']),
					'end_time' => strtotime($item['end_time']),
				];
				$goodsIds = array_column($item['goods'], 'goods_id');
				$goodsInfos = sGoods::Goods($goodsIds,sGoods::FIELDS_GROUP_LIST, ['activity_type' => ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB]);
				foreach ($goodsInfos as $goodsInfo) {
					if ($goodsInfo['status'] == mGoodsBasicInfo::STATUS_APP_NOMAL) $data['goods_list'][] = [
						'id' => $goodsInfo['id'],
						'title' => $goodsInfo['title'],
						'describe' => $item['goods'][$goodsInfo['id']]['describe'],
						'ori_min_price' => $goodsInfo['ori_min_price'],
						'ori_max_price' => $goodsInfo['ori_max_price'],
						'actual_min_price' => $item['goods'][$goodsInfo['id']]['buy_price'],
						'actual_max_price' => $item['goods'][$goodsInfo['id']]['buy_price'],
						'actual_stock' => $goodsInfo['actual_stock'],
						'activity_stock' => $goodsInfo['activity_stock'],
						'cover_img' => $goodsInfo['cover_img'],
						'status' => $goodsInfo['status'],
					];
				}

				break;
			}
		}
		return $data;

	}

	public static function admFalshList($params = [])
	{
        $data = [
            'list' => [],
            'total' => 0,
        ];

        //因为列表页有根据商家id和商品id查询,所以需要先查goods维度表
        $where['shop_id'] = isset($params['AND']['shop_id']) ? $params['AND']['shop_id'] : [];
        $where['goods_id']  = isset($params['AND']['goods_id']) ? $params['AND']['goods_id'] : [];
        $where['status'] = mLimitTimeRobbing::STATUS_NORMAL;
        $where = array_filter($where);
        $robbings = mLimitTimeRobbing::select('*', [
            'AND' => $where
        ]);
        if (!$robbings) return $data;

        // 删除无用信息,查询主表
        unset($params['AND']['shop_id']);
        unset($params['AND']['goods_id']);
        //todo 待与产品负责人确认搜索规则, 这个写法比较......
        if(isset($where['shop_id']) || isset($where['goods_id'])) {
            $flashSaleIds = array_column($robbings, 'flash_sale_id');
            $params['AND']['id'] = array_unique($flashSaleIds);
        }

		$flashSaleWhere = [
		    'AND' => $params['AND'],
            'ORDER' => $params['ORDER'],
            'LIMIT' => $params['LIMIT'],
        ];
		$flashInfos = mFlashSale::select('*',$flashSaleWhere);

		// 最后查询sku维度表
		$robbingids = array_column($robbings, 'id');
		$robbingSkus = mLimitTimeRobbingSku::select('*', [
			'robbing_id' => $robbingids,
			'status' => mLimitTimeRobbingSku::STATUS_NORMAL,
		]);
		$robbingSkusGrpGoodIds = [];
		$skuIds = [];
		foreach ($robbingSkus as $robbingSku) {
			$robbingSkusGrpGoodIds[$robbingSku['robbing_id']][] = $robbingSku;
			$skuIds[] = $robbingSku['sku_id'];
		}

		$skuInfos = Sku::Sku4Order($skuIds);

		$robbingsGrpFlashId = [];
		foreach ($robbings as $robbing) {
			$robbingsGrpFlashId[$robbing['flash_sale_id']][] = $robbing;
		}

		foreach ($flashInfos as $key => $flashInfo) {
			if (isset($robbingsGrpFlashId[$flashInfo['id']])) foreach ($robbingsGrpFlashId[$flashInfo['id']] as $k => $item) {
				if(isset($robbingSkusGrpGoodIds[$item['id']])) {
                    $subsityPrice = 0;
                    foreach ($robbingSkusGrpGoodIds[$item['id']] as $robbingSkusGrpGoodId) {
                        if (isset($skuInfos[$robbingSkusGrpGoodId['sku_id']]['ori_price'])) {
                            $subsityPrice +=  ( $skuInfos[$robbingSkusGrpGoodId['sku_id']]['ori_price'] - $robbingSkusGrpGoodId['buy_price'] ) * $robbingSkusGrpGoodId['start_stock'];
                        }
                    }
                    $robbingsGrpFlashId[$flashInfo['id']][$k]['subsidy_price'] = $subsityPrice;
                    $robbingsGrpFlashId[$flashInfo['id']][$k]['skus'] = $robbingSkusGrpGoodIds[$item['id']];
                }
			}
			if (isset($robbingsGrpFlashId[$flashInfo['id']])) {
				$flashInfos[$key]['goods'] = $robbingsGrpFlashId[$flashInfo['id']];
			} else {
				$flashInfos[$key]['goods'] = [];
			}
		}

        if ($flashInfos) foreach ($flashInfos as $k => $flashSale) {
            $flashInfos[$k]['goods_nums'] = count($flashSale['goods']);
            $flashInfos[$k]['shop_nums'] = count(array_unique( array_column($flashSale['goods'], 'shop_id')));
            $flashInfos[$k]['subsidy_price'] =array_sum(array_unique( array_column($flashSale['goods'], 'subsidy_price')));
            $sku_nums = 0;
            $stocks = 0;
            foreach ($flashSale['goods'] as $good) {
                $sku_nums += isset($good['skus']) ? count($good['skus']) : 0;
                $stocks += isset($good['skus']) ? array_sum(array_column($good['skus'], 'promo_stock')): 0;
            }
            $flashInfos[$k]['sku_nums'] = $sku_nums;
            $flashInfos[$k]['stocks'] = $stocks;
            $flashInfos[$k]['type_desc'] = ActivityInfo::ACTIVITY_TYPES_MAPS[$flashSale['type']] ?? '';
        }

		return $flashInfos ? ['list' => $flashInfos, 'total' => mFlashSale::count('*', $flashSaleWhere['AND'])] : $data;
	}

	public static function mgtFlashSaleTags($goodsIds)
	{
		$Rst = [];
		$RobbingList = mLimitTimeRobbing::getNotOverList($goodsIds);
		foreach ($RobbingList as $goodsId => $Robbings) {
			if (in_array($goodsId, $goodsIds)) {
				foreach ($Robbings as $robbing) {
                    if ($robbing['type'] == ActivityInfo::ACTIVITY_TYPE_ZHUYOUJINTIE) {
                        $Rst[$goodsId][] = "住友津贴 " . date("m-d H:i", strtotime($robbing['start_time']));
                    } else {
                        $Rst[$goodsId][] = "限时购 " . date("m-d H:i", strtotime($robbing['start_time']));
                    }
				}
			}
		}

		return $Rst;
	}

    /**
     * 下载模板
     * @return bool
     * @throws \Exception
     */
	public static function downLoad()
    {
        return FlashSaleExcel::downList();
    }

    /**
     * 上传商品
     * @param $file
     * @param $isConfirm
     * @param $adminId
     * @return array|bool
     * @throws \Exception
     */
    public static function uploadGoods($file, $isConfirm, $adminId)
    {
        try {

            return admFlashSale::upLoadGoods($file, $isConfirm, $adminId);

        } catch (\Exception $e) {

            tLog::debug('批量上传限时购商品出现异常', [
                    $e->getFile(),
                    $e->getLine(),
                    $e->getMessage(),
                ]);
            
            return false;
        }
    }

    /**
     * goods信息页面
     * @param $where
     * @return array
     */
    public static function admFlashSaleGoodsList($where)
    {
        return admFlashSale::admFlashSaleGoodsList($where);
    }

    /**
     * 修改商品维度信息, 不同的信息需要用不同的方式处理
     * @param $flashSaleId
     * @param $robbingId
     * @param $data
     * @return mixed
     */
    public static function flashSaleGoodsSave($flashSaleId, $robbingId, $data)
    {
        try {

            return admFlashSale::flashSaleGoodsSave($flashSaleId, $robbingId, $data);

        } catch (\Exception $e) {

            tLog::debug('修改商品信息出现异常', [
                $e->getFile(),
                $e->getLine(),
                $e->getMessage(),
            ]);

            return ['msg' => $e->getMessage()];
        }
    }

    /**
     * 修改sku维度相关信息
     * @param $flashSaleId
     * @param $robbingId
     * @param $robbingSkuId
     * @param $params
     * @throws \Exception
     */
    public static function flashSaleSkuSave($flashSaleId, $robbingId, $robbingSkuId, $params)
    {
        admFlashSale::flashSaleSkuSave($flashSaleId, $robbingId, $robbingSkuId, $params);
    }

    /**
     * 添加限时抢商品
     * @param $flashSaleId
     * @param $goodsIds
     * @return mixed
     * @throws \Exception
     */
    public static function flashSaleAddGoods($flashSaleId, $goodsIds)
    {
        return admFlashSale::flashSaleAddGoods($flashSaleId, $goodsIds);
    }

    /**
     * 选择sku所需要的数据
     * @param $robbingId
     * @return array
     */
    public static function flashSaleSkuEdit($robbingId)
    {
        return admFlashSale::flashSaleSkuEdit($robbingId);
    }

    /**
     * 获取sku信息
     * @param $where
     * @return array
     */
    public static function admFlashSaleSkuList($where)
    {
        return admFlashSale::admFlashSaleSkuList($where);
    }

    /**
     * 添加限时抢
     * @param $flashSaleId
     * @param $params
     * @return bool
     */
    public static function addFlashSale($flashSaleId, $params)
    {
        return admFlashSale::addFlashSale($flashSaleId, $params);
    }

    /**
     * 修改开始时间或者结束时间
     * @param $flashSaleId
     * @param $params
     * @return bool|mixed
     * @throws \Exception
     */
    public static function saveFlashSaleTime($flashSaleId, $params)
    {
        $timeData = [];
        $flashSale = mFlashSale::get('*', ['id' => $flashSaleId, 'status' => mFlashSale::STATUS_NORMAL]);
        if($params['name'] == 'start_time') {
            $timeData['start_time'] = $params['value'];
            $timeData['end_time'] = $flashSale['end_time'];
        } else if($params['name'] == 'end_time') {
            $timeData['start_time'] = $flashSale['start_time'];
            $timeData['end_time'] = $params['value'];
        } else if($params['name'] == 'preview_start_time') {
            $timeData['start_time'] = $flashSale['start_time'];
            $timeData['end_time'] = $flashSale['end_time'];
            $timeData['preview_start_time'] = $params['value'];
        }

        $result = admFlashSale::saveFlashSale($flashSale , $timeData);

        return $result;
    }

    /**
     * 选择参加限时抢的sku
     * @param $flashSaleId
     * @param $robbingId
     * @param $skuIds
     * @throws \Exception
     */
    public static function saveSkuId($flashSaleId, $robbingId, $skuIds)
    {
        $skuIds = array_filter($skuIds);
        if(!$skuIds) {
            throw new \Exception('未选取sku');
        } else {
            admFlashSale::saveSkuId($flashSaleId, $robbingId, $skuIds);
        }
    }

    /**
     * 删除一场活动
     * @param $flashSaleId
     * @param $adminId
     * @return mixed
     */
    public static function delFlashSale($flashSaleId, $adminId)
    {
        return admFlashSale::delFlashSale($flashSaleId, $adminId);
    }

    /**
     * 删除一个商品
     * @param $flashSaleId
     * @param $robbingId
     * @param $adminId
     * @return mixed
     */
    public static function delFlashSaleGoods($flashSaleId, $robbingId, $adminId)
    {
        return admFlashSale::delFlashSaleGoods($flashSaleId, $robbingId, $adminId);
    }

    /**
     * 删除一个sku
     * @param $flashSaleId
     * @param $robbingId
     * @param $robbingSkuId
     * @param $adminId
     * @return mixed
     */
    public static function delFlashSaleSku($flashSaleId, $robbingId, $robbingSkuId, $adminId)
    {
        return admFlashSale::delFlashSaleSku($flashSaleId, $robbingId, $robbingSkuId, $adminId);
    }

    /**
     * 商品排序
     * @param $flashSaleId
     * @param $sortList
     */
    public static function flashSaleGoodsSort($flashSaleId, $sortList)
    {
        foreach ($sortList['sort'] as $key => $value) {
            mLimitTimeRobbing::update(['order' => $value], ['id' => $key]);
        }
    }
}